Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [9]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [129]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [141]:
import cv2    
import urllib
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[459])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [151]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path, url=False):
    if url:
        req = urllib.request.urlopen(img_path)
        arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
        img = cv2.imdecode(arr, -1) 
    else:
        img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

In [54]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## DONE: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

%time humans_as_humans = sum([int(face_detector(human_file)) for human_file in human_files_short])
%time dogs_as_humans = sum([int(face_detector(dog_file)) for dog_file in dog_files_short])

print(f'{humans_as_humans}% of the first 100 images in human_files have a detected human face')
print(f'{dogs_as_humans}% of the first 100 images in dog_files have a detected human face')
CPU times: user 6.32 s, sys: 0 ns, total: 6.32 s
Wall time: 1.63 s
CPU times: user 34.3 s, sys: 6.68 s, total: 40.9 s
Wall time: 12.1 s
99% of the first 100 images in human_files have a detected human face
12% of the first 100 images in dog_files have a detected human face

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: Considering that the objective of the product is to output an estimate of a dog breed given a dog or human face, the users will more probably expect that they need to provide a frontal view of the face. Furthermore, the Haar cascades are used specifically for face detection, but not general human detection. In case it is necessary to detect humans from other kind of angles, a dataset that represents these cases will be necessary, and although ImageNet does not have a specific human class, the first layers of a pretrained model could still be useful to perform transfer learning.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [6]:
## (Optional) DONE: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

LBP Cascades

In [153]:
lbp_face_cascade = cv2.CascadeClassifier('lbpcascades/lbpcascade_frontalface_improved.xml')

def lbp_face_detector(img_path, url=False):
    if url:
        req = urllib.request.urlopen(img_path)
        arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
        img = cv2.imdecode(arr, -1) 
    else:
        img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = lbp_face_cascade.detectMultiScale(gray)
    return len(faces) > 0
In [56]:
## Test the performance of the lbp_face_detector algorithm 
## on the images in human_files_short and dog_files_short.

%time humans_as_humans = sum([int(lbp_face_detector(human_file)) for human_file in human_files_short])
%time dogs_as_humans = sum([int(lbp_face_detector(dog_file)) for dog_file in dog_files_short])

print(f'{humans_as_humans}% of the first 100 images in human_files have a detected human face')
print(f'{dogs_as_humans}% of the first 100 images in dog_files have a detected human face')
CPU times: user 1.71 s, sys: 0 ns, total: 1.71 s
Wall time: 522 ms
CPU times: user 14.8 s, sys: 0 ns, total: 14.8 s
Wall time: 2.74 s
87% of the first 100 images in human_files have a detected human face
1% of the first 100 images in dog_files have a detected human face

Deep Neural Network (ResNet-10)

In [124]:
net = cv2.dnn.readNetFromCaffe('caffe/deploy.prototxt.txt',
                               'caffe/res10_300x300_ssd_iter_140000.caffemodel')
In [154]:
def dnn_face_detector(img_path, confidence_threshold=0.95, url=False):
    if url:
        req = urllib.request.urlopen(img_path)
        arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
        img = cv2.imdecode(arr, -1) 
    else:
        img = cv2.imread(img_path)
    h, w = img.shape[:2]
    blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)),
                1.0, (300, 300), (104.0, 177.0, 123.0))
    net.setInput(blob)
    faces = net.forward()
    return any([faces[0,0,i,2] > confidence_threshold \
                    for i in range(faces.shape[2])])
In [68]:
## Test the performance of a pretrained ResNet-10 classifier
## on the images in human_files_short and dog_files_short.

%time humans_as_humans = sum([int(dnn_face_detector(human_file, 0.99)) for human_file in human_files_short])
%time dogs_as_humans = sum([int(dnn_face_detector(dog_file, 0.99)) for dog_file in dog_files_short])

print(f'{humans_as_humans}% of the first 100 images in human_files have a detected human face')
print(f'{dogs_as_humans}% of the first 100 images in dog_files have a detected human face')
CPU times: user 8.54 s, sys: 304 ms, total: 8.84 s
Wall time: 2.5 s
CPU times: user 8.51 s, sys: 244 ms, total: 8.75 s
Wall time: 2.46 s
100% of the first 100 images in human_files have a detected human face
4% of the first 100 images in dog_files have a detected human face
In [67]:
## Test the performance of a pretrained ResNet-10 classifier
## on the images in human_files_short and dog_files_short.

%time humans_as_humans = sum([int(dnn_face_detector(human_file, 0.5)) for human_file in human_files_short])
%time dogs_as_humans = sum([int(dnn_face_detector(dog_file, 0.5)) for dog_file in dog_files_short])

print(f'{humans_as_humans}% of the first 100 images in human_files have a detected human face')
print(f'{dogs_as_humans}% of the first 100 images in dog_files have a detected human face')
CPU times: user 8.41 s, sys: 284 ms, total: 8.69 s
Wall time: 2.41 s
CPU times: user 8.13 s, sys: 116 ms, total: 8.25 s
Wall time: 2.38 s
100% of the first 100 images in human_files have a detected human face
54% of the first 100 images in dog_files have a detected human face

Results of experimenting with multiple face detectors:

Method Prediction time (humans) Prediction time (dogs) Face detected (humans) Face detected (dogs)
HAAR Cascades 1.63 s 12.1 s 99% 12%
LBP Cascades 522 ms 2.74 s 87% 1%
ResNet-10 (confidence > 0.99) 2.5 s 2.46 s 100% 4%
ResNet-10 (confidence > 0.5) 2.41 s 2.38 s 100% 54%

As we can see, the deep neural network (ResNet) was able to identify all the human faces even at a high confidence threshold (0.99), achieving high discriminative capacity between human and dog faces, with a similar prediction time for human and dog images because of the resizing applied to both kind of images in order to preprocess them as inputs of the neural net. On the other hand, LBP Cascades showed to be a fast but less accurate face detector. Finally, HAAR cascades speed showed to be affected by the type of images used as input and was able to nearly detect all the human faces. Because of its accuracy and speed, the ResNet model will be considered the method of choice.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [131]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
In [165]:
from keras.preprocessing import image                  
from tqdm import tqdm, tqdm_notebook

def path_to_tensor(img_path, url=False):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm_notebook(img_paths)]
    return np.vstack(list_of_tensors)
In [162]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path, url=False):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path, url))
    return np.argmax(ResNet50_model.predict(img))
In [161]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path, url=False):
    prediction = ResNet50_predict_labels(img_path, url)
    return ((prediction <= 268) & (prediction >= 151)) 

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [7]:
from keras.preprocessing import image                  
from tqdm import tqdm, tqdm_notebook

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm_notebook(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [74]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [75]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [ ]:
### DONE: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

%time humans_as_dogs = sum([int(dog_detector(human_file)) for human_file in human_files_short])
%time dogs_as_dogs = sum([int(dog_detector(dog_file)) for dog_file in dog_files_short])

print(f'{humans_as_dogs}% of the first 100 images in human_files have a detected dog face')
print(f'{dogs_as_dogs}% of the first 100 images in dog_files have a detected dog face')

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [10]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255



(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: A sequence of 4 convolutional modules were used, each module consisted of a convolutional layer with a 5x5 kernel and a stride of 3, with a increasing number of filters (16, 32, 64, 128), under the intuition that reducing the spatial dimensions through the kernel size will approximate translation invariance, and increasing the number of filters will provide space for more higher level features. The module also included a ReLU activation layer to reduce the likelihood of vanishing gradients, a Batch Normalization layer for speeding up the training of the neural network and a Dropout layer (keep_prob=0.5) as a regularization technique for preventing overfitting. Max pooling layers were not considered because of the convolutional layer stride, based on the work of Springenberg et al.(1) and Howard et al.(2). Finally, the last layers consist of a 2D Global Average Pooling layer and a couple of dense layers, in order to find patterns from the extracted image features.

  1. 2015 - Jost Tobias Springenberg, Alexey Dosovitskiy, Thomas Brox, Martin Riedmiller. Striving for Simplicity: The All Convolutional Net
  2. 2017 - Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam. MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications
In [3]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense, Activation, BatchNormalization
from keras.models import Sequential

model = Sequential()

### DONE: Define your architecture.
model.add(Conv2D(16, (5, 5), padding='valid', input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))

model.add(Conv2D(32, (5, 5), strides=3, padding='valid'))
model.add(Activation('relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))

model.add(Conv2D(64, (5, 5), strides=3, padding='valid'))
model.add(Activation('relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))

model.add(Conv2D(128, (5, 5), strides=3, padding='valid'))
model.add(Activation('relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))

model.add(GlobalAveragePooling2D())
model.add(Dense(512))
model.add(Dropout(0.5))
model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_9 (Conv2D)            (None, 220, 220, 16)      1216      
_________________________________________________________________
activation_9 (Activation)    (None, 220, 220, 16)      0         
_________________________________________________________________
batch_normalization_9 (Batch (None, 220, 220, 16)      64        
_________________________________________________________________
dropout_9 (Dropout)          (None, 220, 220, 16)      0         
_________________________________________________________________
conv2d_10 (Conv2D)           (None, 72, 72, 32)        12832     
_________________________________________________________________
activation_10 (Activation)   (None, 72, 72, 32)        0         
_________________________________________________________________
batch_normalization_10 (Batc (None, 72, 72, 32)        128       
_________________________________________________________________
dropout_10 (Dropout)         (None, 72, 72, 32)        0         
_________________________________________________________________
conv2d_11 (Conv2D)           (None, 23, 23, 64)        51264     
_________________________________________________________________
activation_11 (Activation)   (None, 23, 23, 64)        0         
_________________________________________________________________
batch_normalization_11 (Batc (None, 23, 23, 64)        256       
_________________________________________________________________
dropout_11 (Dropout)         (None, 23, 23, 64)        0         
_________________________________________________________________
conv2d_12 (Conv2D)           (None, 7, 7, 128)         204928    
_________________________________________________________________
activation_12 (Activation)   (None, 7, 7, 128)         0         
_________________________________________________________________
batch_normalization_12 (Batc (None, 7, 7, 128)         512       
_________________________________________________________________
dropout_12 (Dropout)         (None, 7, 7, 128)         0         
_________________________________________________________________
global_average_pooling2d_3 ( (None, 128)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 512)               66048     
_________________________________________________________________
dropout_13 (Dropout)         (None, 512)               0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               68229     
=================================================================
Total params: 405,477
Trainable params: 404,997
Non-trainable params: 480
_________________________________________________________________

Compile the Model

In [19]:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [20]:
from keras.callbacks import ModelCheckpoint  

### DONE: specify the number of epochs that you would like to use to train the model.

epochs = 40

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

history = model.fit(train_tensors, train_targets, 
              validation_data=(valid_tensors, valid_targets),
              epochs=epochs, batch_size=256, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.9864 - acc: 0.2486
Epoch 00001: val_loss improved from inf to 6.26468, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 15s 2ms/step - loss: 2.9873 - acc: 0.2487 - val_loss: 6.2647 - val_acc: 0.0994
Epoch 2/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.9188 - acc: 0.2640
Epoch 00002: val_loss improved from 6.26468 to 3.82390, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 14s 2ms/step - loss: 2.9163 - acc: 0.2644 - val_loss: 3.8239 - val_acc: 0.1509
Epoch 3/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.8708 - acc: 0.2679
Epoch 00003: val_loss improved from 3.82390 to 3.62868, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 14s 2ms/step - loss: 2.8723 - acc: 0.2671 - val_loss: 3.6287 - val_acc: 0.1665
Epoch 4/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.8723 - acc: 0.2649
Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 13s 2ms/step - loss: 2.8726 - acc: 0.2651 - val_loss: 3.7756 - val_acc: 0.1796
Epoch 5/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.8311 - acc: 0.2829
Epoch 00005: val_loss improved from 3.62868 to 3.59471, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 14s 2ms/step - loss: 2.8311 - acc: 0.2828 - val_loss: 3.5947 - val_acc: 0.1796
Epoch 6/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.7939 - acc: 0.2850
Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.7942 - acc: 0.2852 - val_loss: 3.6741 - val_acc: 0.1605
Epoch 7/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.7797 - acc: 0.2897
Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.7817 - acc: 0.2897 - val_loss: 3.6670 - val_acc: 0.1641
Epoch 8/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.7375 - acc: 0.3005
Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.7387 - acc: 0.3000 - val_loss: 3.8703 - val_acc: 0.1533
Epoch 9/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.7370 - acc: 0.2996
Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.7383 - acc: 0.2990 - val_loss: 4.6702 - val_acc: 0.0934
Epoch 10/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.7203 - acc: 0.2975
Epoch 00010: val_loss improved from 3.59471 to 3.45169, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 14s 2ms/step - loss: 2.7210 - acc: 0.2972 - val_loss: 3.4517 - val_acc: 0.1976
Epoch 11/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.6862 - acc: 0.3057
Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.6876 - acc: 0.3057 - val_loss: 3.7094 - val_acc: 0.1665
Epoch 12/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.6745 - acc: 0.3108
Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.6750 - acc: 0.3106 - val_loss: 3.7665 - val_acc: 0.1341
Epoch 13/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.6281 - acc: 0.3139
Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.6279 - acc: 0.3138 - val_loss: 3.5918 - val_acc: 0.1796
Epoch 14/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.6500 - acc: 0.3137
Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.6538 - acc: 0.3132 - val_loss: 3.6643 - val_acc: 0.1892
Epoch 15/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.6086 - acc: 0.3175
Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.6108 - acc: 0.3169 - val_loss: 3.7485 - val_acc: 0.1820
Epoch 16/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.5982 - acc: 0.3248
Epoch 00016: val_loss improved from 3.45169 to 3.43089, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 14s 2ms/step - loss: 2.5969 - acc: 0.3254 - val_loss: 3.4309 - val_acc: 0.2180
Epoch 17/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.5750 - acc: 0.3313
Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.5769 - acc: 0.3308 - val_loss: 4.6636 - val_acc: 0.1234
Epoch 18/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.5783 - acc: 0.3250
Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.5786 - acc: 0.3247 - val_loss: 3.5353 - val_acc: 0.1916
Epoch 19/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.5572 - acc: 0.3334
Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.5587 - acc: 0.3331 - val_loss: 4.0068 - val_acc: 0.1305
Epoch 20/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.5304 - acc: 0.3394
Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.5316 - acc: 0.3389 - val_loss: 3.9195 - val_acc: 0.1760
Epoch 21/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.4989 - acc: 0.3450
Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.5019 - acc: 0.3443 - val_loss: 3.7685 - val_acc: 0.1473
Epoch 22/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.5155 - acc: 0.3358
Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.5182 - acc: 0.3353 - val_loss: 3.5758 - val_acc: 0.1808
Epoch 23/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.4723 - acc: 0.3498
Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.4713 - acc: 0.3500 - val_loss: 3.5254 - val_acc: 0.1916
Epoch 24/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.4729 - acc: 0.3472
Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.4746 - acc: 0.3470 - val_loss: 3.6247 - val_acc: 0.2000
Epoch 25/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.4661 - acc: 0.3428
Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.4654 - acc: 0.3433 - val_loss: 3.8054 - val_acc: 0.1749
Epoch 26/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.4521 - acc: 0.3472
Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.4531 - acc: 0.3469 - val_loss: 4.1963 - val_acc: 0.1425
Epoch 27/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.4409 - acc: 0.3612
Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.4434 - acc: 0.3609 - val_loss: 4.2925 - val_acc: 0.1377
Epoch 28/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.4125 - acc: 0.3604
Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.4125 - acc: 0.3608 - val_loss: 3.9984 - val_acc: 0.1701
Epoch 29/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.3804 - acc: 0.3708
Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 14s 2ms/step - loss: 2.3824 - acc: 0.3705 - val_loss: 3.9318 - val_acc: 0.1892
Epoch 30/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.3647 - acc: 0.3708
Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.3672 - acc: 0.3705 - val_loss: 3.7816 - val_acc: 0.1868
Epoch 31/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.3543 - acc: 0.3723
Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.3550 - acc: 0.3722 - val_loss: 3.6207 - val_acc: 0.1928
Epoch 32/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.3339 - acc: 0.3758
Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.3352 - acc: 0.3753 - val_loss: 4.2900 - val_acc: 0.1749
Epoch 33/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.3527 - acc: 0.3756
Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.3529 - acc: 0.3756 - val_loss: 3.6435 - val_acc: 0.1856
Epoch 34/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.3494 - acc: 0.3794
Epoch 00034: val_loss improved from 3.43089 to 3.38973, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 15s 2ms/step - loss: 2.3503 - acc: 0.3792 - val_loss: 3.3897 - val_acc: 0.1772
Epoch 35/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.3269 - acc: 0.3779
Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.3267 - acc: 0.3783 - val_loss: 3.4723 - val_acc: 0.2156
Epoch 36/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.2913 - acc: 0.3890
Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.2955 - acc: 0.3888 - val_loss: 3.9488 - val_acc: 0.1796
Epoch 37/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.2885 - acc: 0.3858
Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.2893 - acc: 0.3856 - val_loss: 3.6580 - val_acc: 0.2012
Epoch 38/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.2940 - acc: 0.3863
Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.2949 - acc: 0.3858 - val_loss: 3.7836 - val_acc: 0.1760
Epoch 39/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.2904 - acc: 0.3849
Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.2928 - acc: 0.3846 - val_loss: 3.9557 - val_acc: 0.1796
Epoch 40/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.2584 - acc: 0.3941
Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 15s 2ms/step - loss: 2.2600 - acc: 0.3934 - val_loss: 5.2111 - val_acc: 0.1030
In [21]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set()

def plot_losses(train_loss, val_loss, scale):
    plt.figure(figsize=(10,5))
    plt.plot(train_loss)
    plt.plot([(x + 1) * scale - 1 for x in range(len(val_loss))], val_loss)
    plt.legend(['train loss', 'validation loss'])
In [30]:
plot_losses(history.history['loss'], history.history['val_loss'], 1.0)

Load the Model with the Best Validation Loss

In [31]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [32]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 19.9761%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [14]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [15]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [16]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [18]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=40, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6600/6680 [============================>.] - ETA: 0s - loss: 5.8393 - acc: 0.6259
Epoch 00001: val_loss improved from inf to 6.88083, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 169us/step - loss: 5.8272 - acc: 0.6263 - val_loss: 6.8808 - val_acc: 0.4754
Epoch 2/40
6380/6680 [===========================>..] - ETA: 0s - loss: 5.7336 - acc: 0.6353
Epoch 00002: val_loss did not improve
6680/6680 [==============================] - 1s 139us/step - loss: 5.7986 - acc: 0.6316 - val_loss: 6.9386 - val_acc: 0.4766
Epoch 3/40
6500/6680 [============================>.] - ETA: 0s - loss: 5.8238 - acc: 0.6322
Epoch 00003: val_loss improved from 6.88083 to 6.87993, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 155us/step - loss: 5.7837 - acc: 0.6343 - val_loss: 6.8799 - val_acc: 0.4898
Epoch 4/40
6600/6680 [============================>.] - ETA: 0s - loss: 5.7733 - acc: 0.6362
Epoch 00004: val_loss improved from 6.87993 to 6.87039, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 152us/step - loss: 5.7727 - acc: 0.6362 - val_loss: 6.8704 - val_acc: 0.4826
Epoch 5/40
6400/6680 [===========================>..] - ETA: 0s - loss: 5.7670 - acc: 0.6381
Epoch 00005: val_loss improved from 6.87039 to 6.79696, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 147us/step - loss: 5.7676 - acc: 0.6377 - val_loss: 6.7970 - val_acc: 0.4910
Epoch 6/40
6460/6680 [============================>.] - ETA: 0s - loss: 5.7641 - acc: 0.6376
Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 1s 137us/step - loss: 5.7467 - acc: 0.6386 - val_loss: 6.8120 - val_acc: 0.4886
Epoch 7/40
6520/6680 [============================>.] - ETA: 0s - loss: 5.6239 - acc: 0.6388
Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 1s 135us/step - loss: 5.6098 - acc: 0.6395 - val_loss: 6.8052 - val_acc: 0.4886
Epoch 8/40
6640/6680 [============================>.] - ETA: 0s - loss: 5.4934 - acc: 0.6459
Epoch 00008: val_loss improved from 6.79696 to 6.59751, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 150us/step - loss: 5.4924 - acc: 0.6460 - val_loss: 6.5975 - val_acc: 0.5078
Epoch 9/40
6500/6680 [============================>.] - ETA: 0s - loss: 5.3686 - acc: 0.6523
Epoch 00009: val_loss improved from 6.59751 to 6.50842, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 149us/step - loss: 5.3755 - acc: 0.6518 - val_loss: 6.5084 - val_acc: 0.5174
Epoch 10/40
6320/6680 [===========================>..] - ETA: 0s - loss: 5.2391 - acc: 0.6644
Epoch 00010: val_loss improved from 6.50842 to 6.47848, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 149us/step - loss: 5.2509 - acc: 0.6635 - val_loss: 6.4785 - val_acc: 0.5102
Epoch 11/40
6520/6680 [============================>.] - ETA: 0s - loss: 5.0786 - acc: 0.6693
Epoch 00011: val_loss improved from 6.47848 to 6.26894, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 144us/step - loss: 5.0801 - acc: 0.6696 - val_loss: 6.2689 - val_acc: 0.5246
Epoch 12/40
6380/6680 [===========================>..] - ETA: 0s - loss: 4.9034 - acc: 0.6850
Epoch 00012: val_loss improved from 6.26894 to 6.21898, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 140us/step - loss: 4.9137 - acc: 0.6838 - val_loss: 6.2190 - val_acc: 0.5329
Epoch 13/40
6420/6680 [===========================>..] - ETA: 0s - loss: 4.8699 - acc: 0.6879
Epoch 00013: val_loss improved from 6.21898 to 6.11789, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 152us/step - loss: 4.8538 - acc: 0.6889 - val_loss: 6.1179 - val_acc: 0.5293
Epoch 14/40
6260/6680 [===========================>..] - ETA: 0s - loss: 4.7231 - acc: 0.6946
Epoch 00014: val_loss improved from 6.11789 to 6.11238, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 143us/step - loss: 4.7549 - acc: 0.6924 - val_loss: 6.1124 - val_acc: 0.5293
Epoch 15/40
6360/6680 [===========================>..] - ETA: 0s - loss: 4.6234 - acc: 0.6995
Epoch 00015: val_loss improved from 6.11238 to 6.02042, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 152us/step - loss: 4.6529 - acc: 0.6981 - val_loss: 6.0204 - val_acc: 0.5353
Epoch 16/40
6360/6680 [===========================>..] - ETA: 0s - loss: 4.5532 - acc: 0.7071
Epoch 00016: val_loss improved from 6.02042 to 5.96772, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 149us/step - loss: 4.5606 - acc: 0.7067 - val_loss: 5.9677 - val_acc: 0.5401
Epoch 17/40
6620/6680 [============================>.] - ETA: 0s - loss: 4.5334 - acc: 0.7104
Epoch 00017: val_loss improved from 5.96772 to 5.86728, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 153us/step - loss: 4.5318 - acc: 0.7105 - val_loss: 5.8673 - val_acc: 0.5413
Epoch 18/40
6580/6680 [============================>.] - ETA: 0s - loss: 4.5201 - acc: 0.7132
Epoch 00018: val_loss improved from 5.86728 to 5.82318, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 137us/step - loss: 4.5104 - acc: 0.7139 - val_loss: 5.8232 - val_acc: 0.5485
Epoch 19/40
6540/6680 [============================>.] - ETA: 0s - loss: 4.4712 - acc: 0.7150
Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 1s 135us/step - loss: 4.4721 - acc: 0.7150 - val_loss: 5.8773 - val_acc: 0.5509
Epoch 20/40
6500/6680 [============================>.] - ETA: 0s - loss: 4.4015 - acc: 0.7189
Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 1s 138us/step - loss: 4.4093 - acc: 0.7186 - val_loss: 5.9099 - val_acc: 0.5425
Epoch 21/40
6380/6680 [===========================>..] - ETA: 0s - loss: 4.4012 - acc: 0.7213
Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 1s 154us/step - loss: 4.3906 - acc: 0.7219 - val_loss: 5.8465 - val_acc: 0.5413
Epoch 22/40
6620/6680 [============================>.] - ETA: 0s - loss: 4.3821 - acc: 0.7230
Epoch 00022: val_loss improved from 5.82318 to 5.80882, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 136us/step - loss: 4.3814 - acc: 0.7231 - val_loss: 5.8088 - val_acc: 0.5473
Epoch 23/40
6640/6680 [============================>.] - ETA: 0s - loss: 4.3725 - acc: 0.7245
Epoch 00023: val_loss improved from 5.80882 to 5.75495, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 143us/step - loss: 4.3680 - acc: 0.7249 - val_loss: 5.7550 - val_acc: 0.5581
Epoch 24/40
6600/6680 [============================>.] - ETA: 0s - loss: 4.3557 - acc: 0.7250
Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 1s 135us/step - loss: 4.3512 - acc: 0.7253 - val_loss: 5.9307 - val_acc: 0.5401
Epoch 25/40
6540/6680 [============================>.] - ETA: 0s - loss: 4.1968 - acc: 0.7252
Epoch 00025: val_loss improved from 5.75495 to 5.75312, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 145us/step - loss: 4.1876 - acc: 0.7260 - val_loss: 5.7531 - val_acc: 0.5485
Epoch 26/40
6420/6680 [===========================>..] - ETA: 0s - loss: 4.0565 - acc: 0.7374
Epoch 00026: val_loss improved from 5.75312 to 5.68444, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 159us/step - loss: 4.0351 - acc: 0.7388 - val_loss: 5.6844 - val_acc: 0.5437
Epoch 27/40
6640/6680 [============================>.] - ETA: 0s - loss: 3.9839 - acc: 0.7453
Epoch 00027: val_loss improved from 5.68444 to 5.51838, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 150us/step - loss: 3.9817 - acc: 0.7455 - val_loss: 5.5184 - val_acc: 0.5689
Epoch 28/40
6300/6680 [===========================>..] - ETA: 0s - loss: 3.9425 - acc: 0.7508
Epoch 00028: val_loss improved from 5.51838 to 5.48190, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 135us/step - loss: 3.9600 - acc: 0.7494 - val_loss: 5.4819 - val_acc: 0.5749
Epoch 29/40
6420/6680 [===========================>..] - ETA: 0s - loss: 3.9174 - acc: 0.7505
Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 1s 138us/step - loss: 3.9131 - acc: 0.7509 - val_loss: 5.5036 - val_acc: 0.5665
Epoch 30/40
6440/6680 [===========================>..] - ETA: 0s - loss: 3.8277 - acc: 0.7542
Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 1s 138us/step - loss: 3.8079 - acc: 0.7551 - val_loss: 5.5692 - val_acc: 0.5689
Epoch 31/40
6360/6680 [===========================>..] - ETA: 0s - loss: 3.7096 - acc: 0.7629
Epoch 00031: val_loss improved from 5.48190 to 5.37698, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 140us/step - loss: 3.6825 - acc: 0.7648 - val_loss: 5.3770 - val_acc: 0.5892
Epoch 32/40
6460/6680 [============================>.] - ETA: 0s - loss: 3.6717 - acc: 0.7684
Epoch 00032: val_loss improved from 5.37698 to 5.34462, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 140us/step - loss: 3.6597 - acc: 0.7692 - val_loss: 5.3446 - val_acc: 0.5856
Epoch 33/40
6520/6680 [============================>.] - ETA: 0s - loss: 3.6571 - acc: 0.7707
Epoch 00033: val_loss improved from 5.34462 to 5.32195, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 147us/step - loss: 3.6516 - acc: 0.7711 - val_loss: 5.3219 - val_acc: 0.5868
Epoch 34/40
6460/6680 [============================>.] - ETA: 0s - loss: 3.6457 - acc: 0.7718
Epoch 00034: val_loss improved from 5.32195 to 5.31410, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 131us/step - loss: 3.6487 - acc: 0.7717 - val_loss: 5.3141 - val_acc: 0.5844
Epoch 35/40
6380/6680 [===========================>..] - ETA: 0s - loss: 3.6603 - acc: 0.7708
Epoch 00035: val_loss improved from 5.31410 to 5.24148, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 134us/step - loss: 3.6489 - acc: 0.7716 - val_loss: 5.2415 - val_acc: 0.6036
Epoch 36/40
6660/6680 [============================>.] - ETA: 0s - loss: 3.6467 - acc: 0.7725
Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 1s 148us/step - loss: 3.6453 - acc: 0.7726 - val_loss: 5.2954 - val_acc: 0.6024
Epoch 37/40
6380/6680 [===========================>..] - ETA: 0s - loss: 3.6233 - acc: 0.7743
Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 1s 156us/step - loss: 3.6440 - acc: 0.7731 - val_loss: 5.2988 - val_acc: 0.5928
Epoch 38/40
6520/6680 [============================>.] - ETA: 0s - loss: 3.6176 - acc: 0.7753
Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 1s 144us/step - loss: 3.6430 - acc: 0.7737 - val_loss: 5.2616 - val_acc: 0.6036
Epoch 39/40
6320/6680 [===========================>..] - ETA: 0s - loss: 3.6371 - acc: 0.7736
Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 1s 150us/step - loss: 3.6399 - acc: 0.7734 - val_loss: 5.3402 - val_acc: 0.5880
Epoch 40/40
6440/6680 [===========================>..] - ETA: 0s - loss: 3.6435 - acc: 0.7733
Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 1s 151us/step - loss: 3.6402 - acc: 0.7735 - val_loss: 5.3392 - val_acc: 0.5964
Out[18]:
<keras.callbacks.History at 0x7f6999efbcf8>

Load the Model with the Best Validation Loss

In [19]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [20]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 61.3636%

Predict Dog Breed with the Model

In [21]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [34]:
### DONE: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load(f'bottleneck_features/DogResnet50Data.npz')
train_Resnet50 = bottleneck_features['train']
valid_Resnet50 = bottleneck_features['valid']
test_Resnet50 = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: The architecture was based on the top layers of the previous CNN (Question 4). As such it consists mainly of dense layers, in order to analyze the interactions between all the high level features, and dropout layers, in order to prevent overfitting. As these are the last layers, it is not necessary to make the CNN very deep, which was verified by increasing the number of layers and experiencing an actual drop in performance.

In [92]:
### DONE: Define your architecture.
Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(Dropout(0.3))
Resnet50_model.add(Dense(512, activation='relu'))
Resnet50_model.add(Dropout(0.3))
Resnet50_model.add(Dense(133, activation='softmax'))

Resnet50_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_15  (None, 2048)              0         
_________________________________________________________________
dropout_34 (Dropout)         (None, 2048)              0         
_________________________________________________________________
dense_27 (Dense)             (None, 512)               1049088   
_________________________________________________________________
dropout_35 (Dropout)         (None, 512)               0         
_________________________________________________________________
dense_28 (Dense)             (None, 133)               68229     
=================================================================
Total params: 1,117,317
Trainable params: 1,117,317
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [93]:
### DONE: Compile the model.
Resnet50_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [94]:
### DONE: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5', 
                               verbose=1, save_best_only=True)

Resnet50_model.fit(train_Resnet50, train_targets, 
          validation_data=(valid_Resnet50, valid_targets),
          epochs=40, batch_size=256, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6656/6680 [============================>.] - ETA: 0s - loss: 3.5455 - acc: 0.2511
Epoch 00001: val_loss improved from inf to 1.43197, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 227us/step - loss: 3.5406 - acc: 0.2518 - val_loss: 1.4320 - val_acc: 0.6240
Epoch 2/40
3584/6680 [===============>..............] - ETA: 0s - loss: 1.5234 - acc: 0.5776
Epoch 00002: val_loss improved from 1.43197 to 0.88642, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 0s 22us/step - loss: 1.3446 - acc: 0.6186 - val_loss: 0.8864 - val_acc: 0.7437
Epoch 3/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.8840 - acc: 0.7399
Epoch 00003: val_loss improved from 0.88642 to 0.71095, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 0s 22us/step - loss: 0.8844 - acc: 0.7395 - val_loss: 0.7110 - val_acc: 0.7737
Epoch 4/40
3584/6680 [===============>..............] - ETA: 0s - loss: 0.6988 - acc: 0.7879
Epoch 00004: val_loss improved from 0.71095 to 0.66366, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 0s 20us/step - loss: 0.6909 - acc: 0.7928 - val_loss: 0.6637 - val_acc: 0.7856
Epoch 5/40
4864/6680 [====================>.........] - ETA: 0s - loss: 0.5481 - acc: 0.8275
Epoch 00005: val_loss improved from 0.66366 to 0.61468, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 0s 30us/step - loss: 0.5517 - acc: 0.8251 - val_loss: 0.6147 - val_acc: 0.8072
Epoch 6/40
5888/6680 [=========================>....] - ETA: 0s - loss: 0.4428 - acc: 0.8578
Epoch 00006: val_loss improved from 0.61468 to 0.59360, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 0s 24us/step - loss: 0.4498 - acc: 0.8572 - val_loss: 0.5936 - val_acc: 0.8012
Epoch 7/40
4352/6680 [==================>...........] - ETA: 0s - loss: 0.4078 - acc: 0.8745
Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 0s 14us/step - loss: 0.3987 - acc: 0.8765 - val_loss: 0.5944 - val_acc: 0.7988
Epoch 8/40
4352/6680 [==================>...........] - ETA: 0s - loss: 0.3475 - acc: 0.8842
Epoch 00008: val_loss improved from 0.59360 to 0.56065, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 0s 16us/step - loss: 0.3378 - acc: 0.8882 - val_loss: 0.5606 - val_acc: 0.8084
Epoch 9/40
4608/6680 [===================>..........] - ETA: 0s - loss: 0.3196 - acc: 0.8965
Epoch 00009: val_loss improved from 0.56065 to 0.54577, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 0s 17us/step - loss: 0.3133 - acc: 0.8969 - val_loss: 0.5458 - val_acc: 0.8216
Epoch 10/40
4096/6680 [=================>............] - ETA: 0s - loss: 0.2735 - acc: 0.9141
Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 0s 15us/step - loss: 0.2722 - acc: 0.9135 - val_loss: 0.5515 - val_acc: 0.8263
Epoch 11/40
4608/6680 [===================>..........] - ETA: 0s - loss: 0.2524 - acc: 0.9223
Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 0s 14us/step - loss: 0.2494 - acc: 0.9238 - val_loss: 0.5513 - val_acc: 0.8240
Epoch 12/40
4096/6680 [=================>............] - ETA: 0s - loss: 0.2086 - acc: 0.9375
Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 0s 16us/step - loss: 0.2147 - acc: 0.9338 - val_loss: 0.5546 - val_acc: 0.8192
Epoch 13/40
4096/6680 [=================>............] - ETA: 0s - loss: 0.2262 - acc: 0.9309
Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 0s 14us/step - loss: 0.2233 - acc: 0.9320 - val_loss: 0.5712 - val_acc: 0.8144
Epoch 14/40
4096/6680 [=================>............] - ETA: 0s - loss: 0.1972 - acc: 0.9380
Epoch 00014: val_loss improved from 0.54577 to 0.52995, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 0s 21us/step - loss: 0.1901 - acc: 0.9389 - val_loss: 0.5299 - val_acc: 0.8335
Epoch 15/40
4608/6680 [===================>..........] - ETA: 0s - loss: 0.1843 - acc: 0.9440
Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 0s 23us/step - loss: 0.1874 - acc: 0.9431 - val_loss: 0.5452 - val_acc: 0.8383
Epoch 16/40
4352/6680 [==================>...........] - ETA: 0s - loss: 0.1624 - acc: 0.9490
Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 0s 17us/step - loss: 0.1583 - acc: 0.9493 - val_loss: 0.5343 - val_acc: 0.8347
Epoch 17/40
6400/6680 [===========================>..] - ETA: 0s - loss: 0.1530 - acc: 0.9558
Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 0s 19us/step - loss: 0.1548 - acc: 0.9543 - val_loss: 0.5644 - val_acc: 0.8240
Epoch 18/40
4352/6680 [==================>...........] - ETA: 0s - loss: 0.1565 - acc: 0.9504
Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 0s 13us/step - loss: 0.1534 - acc: 0.9534 - val_loss: 0.5389 - val_acc: 0.8395
Epoch 19/40
4864/6680 [====================>.........] - ETA: 0s - loss: 0.1282 - acc: 0.9618
Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 0s 13us/step - loss: 0.1211 - acc: 0.9645 - val_loss: 0.5394 - val_acc: 0.8240
Epoch 20/40
4608/6680 [===================>..........] - ETA: 0s - loss: 0.1158 - acc: 0.9648
Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 0s 13us/step - loss: 0.1205 - acc: 0.9632 - val_loss: 0.5364 - val_acc: 0.8407
Epoch 21/40
3840/6680 [================>.............] - ETA: 0s - loss: 0.1404 - acc: 0.9578
Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 0s 16us/step - loss: 0.1379 - acc: 0.9587 - val_loss: 0.5541 - val_acc: 0.8216
Epoch 22/40
4608/6680 [===================>..........] - ETA: 0s - loss: 0.1375 - acc: 0.9583
Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 0s 14us/step - loss: 0.1348 - acc: 0.9591 - val_loss: 0.5353 - val_acc: 0.8287
Epoch 23/40
4352/6680 [==================>...........] - ETA: 0s - loss: 0.1059 - acc: 0.9704
Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 0s 14us/step - loss: 0.1078 - acc: 0.9681 - val_loss: 0.5390 - val_acc: 0.8431
Epoch 24/40
3840/6680 [================>.............] - ETA: 0s - loss: 0.1052 - acc: 0.9680
Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 0s 15us/step - loss: 0.1073 - acc: 0.9674 - val_loss: 0.5531 - val_acc: 0.8251
Epoch 25/40
4608/6680 [===================>..........] - ETA: 0s - loss: 0.0959 - acc: 0.9707
Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 0s 13us/step - loss: 0.0947 - acc: 0.9708 - val_loss: 0.5309 - val_acc: 0.8311
Epoch 26/40
4608/6680 [===================>..........] - ETA: 0s - loss: 0.0925 - acc: 0.9729
Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 0s 13us/step - loss: 0.0926 - acc: 0.9732 - val_loss: 0.5555 - val_acc: 0.8407
Epoch 27/40
5376/6680 [=======================>......] - ETA: 0s - loss: 0.0836 - acc: 0.9749
Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 0s 21us/step - loss: 0.0874 - acc: 0.9734 - val_loss: 0.5346 - val_acc: 0.8347
Epoch 28/40
4352/6680 [==================>...........] - ETA: 0s - loss: 0.0926 - acc: 0.9706
Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 0s 14us/step - loss: 0.0894 - acc: 0.9717 - val_loss: 0.5501 - val_acc: 0.8419
Epoch 29/40
5376/6680 [=======================>......] - ETA: 0s - loss: 0.0813 - acc: 0.9767
Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 0s 22us/step - loss: 0.0798 - acc: 0.9769 - val_loss: 0.5705 - val_acc: 0.8299
Epoch 30/40
4352/6680 [==================>...........] - ETA: 0s - loss: 0.0702 - acc: 0.9809
Epoch 00030: val_loss improved from 0.52995 to 0.51938, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 0s 17us/step - loss: 0.0717 - acc: 0.9793 - val_loss: 0.5194 - val_acc: 0.8431
Epoch 31/40
3840/6680 [================>.............] - ETA: 0s - loss: 0.0602 - acc: 0.9833
Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 0s 15us/step - loss: 0.0611 - acc: 0.9823 - val_loss: 0.5384 - val_acc: 0.8407
Epoch 32/40
4608/6680 [===================>..........] - ETA: 0s - loss: 0.0786 - acc: 0.9755
Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 0s 13us/step - loss: 0.0761 - acc: 0.9760 - val_loss: 0.5826 - val_acc: 0.8395
Epoch 33/40
4096/6680 [=================>............] - ETA: 0s - loss: 0.0685 - acc: 0.9790
Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 0s 15us/step - loss: 0.0685 - acc: 0.9789 - val_loss: 0.5473 - val_acc: 0.8503
Epoch 34/40
4608/6680 [===================>..........] - ETA: 0s - loss: 0.0750 - acc: 0.9787
Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 0s 14us/step - loss: 0.0768 - acc: 0.9768 - val_loss: 0.5666 - val_acc: 0.8359
Epoch 35/40
4352/6680 [==================>...........] - ETA: 0s - loss: 0.0683 - acc: 0.9818
Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 0s 14us/step - loss: 0.0640 - acc: 0.9829 - val_loss: 0.5680 - val_acc: 0.8287
Epoch 36/40
4096/6680 [=================>............] - ETA: 0s - loss: 0.0652 - acc: 0.9807
Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 0s 14us/step - loss: 0.0636 - acc: 0.9814 - val_loss: 0.5690 - val_acc: 0.8311
Epoch 37/40
3840/6680 [================>.............] - ETA: 0s - loss: 0.0600 - acc: 0.9823
Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 0s 15us/step - loss: 0.0581 - acc: 0.9823 - val_loss: 0.5650 - val_acc: 0.8275
Epoch 38/40
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0759 - acc: 0.9775
Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 0s 20us/step - loss: 0.0757 - acc: 0.9775 - val_loss: 0.5975 - val_acc: 0.8335
Epoch 39/40
3840/6680 [================>.............] - ETA: 0s - loss: 0.0632 - acc: 0.9810
Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 0s 15us/step - loss: 0.0669 - acc: 0.9793 - val_loss: 0.5424 - val_acc: 0.8503
Epoch 40/40
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0675 - acc: 0.9816
Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 0s 19us/step - loss: 0.0671 - acc: 0.9814 - val_loss: 0.5758 - val_acc: 0.8383
Out[94]:
<keras.callbacks.History at 0x7fa8953b45f8>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [95]:
### DONE: Load the model weights with the best validation loss.
Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [96]:
### DONE: Calculate classification accuracy on the test dataset.
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Resnet50 Test accuracy: %.4f%%' % test_accuracy)
Resnet50 Test accuracy: 83.3732%
In [112]:
def evaluate_model(model_name):
    bottleneck_features = np.load(f'bottleneck_features/Dog{model_name}Data.npz')
    train = bottleneck_features['train']
    valid = bottleneck_features['valid']
    test = bottleneck_features['test']
    
    model = Sequential()
    model.add(GlobalAveragePooling2D(input_shape=train.shape[1:]))
    model.add(Dropout(0.3))
    model.add(Dense(512, activation='relu'))
    model.add(Dropout(0.3))
    model.add(Dense(133, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    
    checkpointer = ModelCheckpoint(filepath=f'saved_models/weights.best.{model_name}.hdf5', 
                               verbose=1, save_best_only=True)
    model.fit(train, train_targets, 
              validation_data=(valid, valid_targets),
              epochs=40, batch_size=256, callbacks=[checkpointer], verbose=1)
    model.load_weights(f'saved_models/weights.best.{model_name}.hdf5')
    
    predictions = [np.argmax(model.predict(np.expand_dims(feature, axis=0))) for feature in test]
    test_accuracy = 100*np.sum(np.array(predictions)==np.argmax(test_targets, axis=1))/len(predictions)
    print()
    print(f'{model_name} Test accuracy: %.4f%%' % test_accuracy)

Test InceptionV3

In [113]:
evaluate_model('InceptionV3')
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.5715 - acc: 0.4518
Epoch 00001: val_loss improved from inf to 0.67998, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 4s 553us/step - loss: 2.5654 - acc: 0.4527 - val_loss: 0.6800 - val_acc: 0.7952
Epoch 2/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.8229 - acc: 0.7598
Epoch 00002: val_loss improved from 0.67998 to 0.54929, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 2s 338us/step - loss: 0.8212 - acc: 0.7602 - val_loss: 0.5493 - val_acc: 0.8275
Epoch 3/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.5906 - acc: 0.8179
Epoch 00003: val_loss improved from 0.54929 to 0.54551, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 2s 319us/step - loss: 0.5891 - acc: 0.8184 - val_loss: 0.5455 - val_acc: 0.8371
Epoch 4/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.5083 - acc: 0.8392
Epoch 00004: val_loss improved from 0.54551 to 0.53323, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 2s 339us/step - loss: 0.5075 - acc: 0.8392 - val_loss: 0.5332 - val_acc: 0.8371
Epoch 5/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.4375 - acc: 0.8591
Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s 319us/step - loss: 0.4373 - acc: 0.8588 - val_loss: 0.5621 - val_acc: 0.8299
Epoch 6/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.3982 - acc: 0.8696
Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 2s 328us/step - loss: 0.3997 - acc: 0.8689 - val_loss: 0.5380 - val_acc: 0.8467
Epoch 7/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.3830 - acc: 0.8762
Epoch 00007: val_loss improved from 0.53323 to 0.52130, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 2s 338us/step - loss: 0.3822 - acc: 0.8765 - val_loss: 0.5213 - val_acc: 0.8551
Epoch 8/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.3217 - acc: 0.8915
Epoch 00008: val_loss improved from 0.52130 to 0.50271, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 2s 323us/step - loss: 0.3210 - acc: 0.8918 - val_loss: 0.5027 - val_acc: 0.8515
Epoch 9/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2793 - acc: 0.9087
Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 324us/step - loss: 0.2790 - acc: 0.9088 - val_loss: 0.5270 - val_acc: 0.8419
Epoch 10/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2543 - acc: 0.9156
Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 0.2540 - acc: 0.9157 - val_loss: 0.5341 - val_acc: 0.8431
Epoch 11/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2503 - acc: 0.9138
Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 326us/step - loss: 0.2502 - acc: 0.9138 - val_loss: 0.5473 - val_acc: 0.8491
Epoch 12/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2194 - acc: 0.9255
Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.2197 - acc: 0.9253 - val_loss: 0.5555 - val_acc: 0.8443
Epoch 13/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2091 - acc: 0.9291
Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 317us/step - loss: 0.2092 - acc: 0.9290 - val_loss: 0.5570 - val_acc: 0.8551
Epoch 14/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2130 - acc: 0.9286
Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s 323us/step - loss: 0.2133 - acc: 0.9284 - val_loss: 0.5371 - val_acc: 0.8479
Epoch 15/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1901 - acc: 0.9386
Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.1905 - acc: 0.9383 - val_loss: 0.5166 - val_acc: 0.8479
Epoch 16/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1805 - acc: 0.9404
Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 325us/step - loss: 0.1805 - acc: 0.9403 - val_loss: 0.5454 - val_acc: 0.8551
Epoch 17/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1752 - acc: 0.9395
Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 327us/step - loss: 0.1753 - acc: 0.9392 - val_loss: 0.5607 - val_acc: 0.8467
Epoch 18/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1603 - acc: 0.9443
Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 321us/step - loss: 0.1600 - acc: 0.9443 - val_loss: 0.5504 - val_acc: 0.8491
Epoch 19/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1409 - acc: 0.9504
Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 334us/step - loss: 0.1407 - acc: 0.9504 - val_loss: 0.5338 - val_acc: 0.8599
Epoch 20/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1362 - acc: 0.9515
Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 322us/step - loss: 0.1360 - acc: 0.9515 - val_loss: 0.5414 - val_acc: 0.8575
Epoch 21/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1296 - acc: 0.9561
Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 2s 341us/step - loss: 0.1298 - acc: 0.9560 - val_loss: 0.5886 - val_acc: 0.8527
Epoch 22/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1327 - acc: 0.9539
Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.1328 - acc: 0.9537 - val_loss: 0.5592 - val_acc: 0.8587
Epoch 23/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1172 - acc: 0.9620
Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 2s 328us/step - loss: 0.1175 - acc: 0.9617 - val_loss: 0.5540 - val_acc: 0.8611
Epoch 24/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1285 - acc: 0.9557
Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 2s 322us/step - loss: 0.1284 - acc: 0.9555 - val_loss: 0.5769 - val_acc: 0.8479
Epoch 25/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1093 - acc: 0.9636
Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 2s 323us/step - loss: 0.1093 - acc: 0.9636 - val_loss: 0.5824 - val_acc: 0.8527
Epoch 26/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1080 - acc: 0.9627
Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 2s 342us/step - loss: 0.1076 - acc: 0.9629 - val_loss: 0.6106 - val_acc: 0.8539
Epoch 27/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0922 - acc: 0.9686
Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 2s 322us/step - loss: 0.0928 - acc: 0.9686 - val_loss: 0.6074 - val_acc: 0.8455
Epoch 28/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0960 - acc: 0.9716
Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 2s 332us/step - loss: 0.0959 - acc: 0.9716 - val_loss: 0.6011 - val_acc: 0.8503
Epoch 29/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0937 - acc: 0.9698
Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 2s 345us/step - loss: 0.0938 - acc: 0.9698 - val_loss: 0.5930 - val_acc: 0.8551
Epoch 30/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1022 - acc: 0.9647
Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 2s 330us/step - loss: 0.1023 - acc: 0.9647 - val_loss: 0.6287 - val_acc: 0.8395
Epoch 31/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1010 - acc: 0.9663
Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 2s 352us/step - loss: 0.1007 - acc: 0.9665 - val_loss: 0.6119 - val_acc: 0.8491
Epoch 32/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0877 - acc: 0.9727
Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 2s 316us/step - loss: 0.0878 - acc: 0.9726 - val_loss: 0.6135 - val_acc: 0.8503
Epoch 33/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0863 - acc: 0.9719
Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 2s 345us/step - loss: 0.0862 - acc: 0.9719 - val_loss: 0.6531 - val_acc: 0.8479
Epoch 34/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0802 - acc: 0.9725
Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 2s 346us/step - loss: 0.0803 - acc: 0.9726 - val_loss: 0.6303 - val_acc: 0.8551
Epoch 35/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0757 - acc: 0.9757
Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 2s 338us/step - loss: 0.0755 - acc: 0.9757 - val_loss: 0.6103 - val_acc: 0.8539
Epoch 36/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0646 - acc: 0.9803
Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 2s 335us/step - loss: 0.0647 - acc: 0.9802 - val_loss: 0.6338 - val_acc: 0.8491
Epoch 37/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0714 - acc: 0.9778
Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 2s 314us/step - loss: 0.0713 - acc: 0.9778 - val_loss: 0.6243 - val_acc: 0.8527
Epoch 38/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0661 - acc: 0.9769
Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 2s 326us/step - loss: 0.0662 - acc: 0.9768 - val_loss: 0.6441 - val_acc: 0.8455
Epoch 39/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0733 - acc: 0.9764
Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 2s 319us/step - loss: 0.0732 - acc: 0.9765 - val_loss: 0.6413 - val_acc: 0.8551
Epoch 40/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0655 - acc: 0.9785
Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 2s 313us/step - loss: 0.0654 - acc: 0.9786 - val_loss: 0.6327 - val_acc: 0.8479

InceptionV3 Test accuracy: 82.1770%

Test Xception

In [114]:
evaluate_model('Xception')
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6656/6680 [============================>.] - ETA: 0s - loss: 2.5827 - acc: 0.4737
Epoch 00001: val_loss improved from inf to 0.76704, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s 1ms/step - loss: 2.5763 - acc: 0.4751 - val_loss: 0.7670 - val_acc: 0.7701
Epoch 2/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.7288 - acc: 0.7797
Epoch 00002: val_loss improved from 0.76704 to 0.56306, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 506us/step - loss: 0.7281 - acc: 0.7801 - val_loss: 0.5631 - val_acc: 0.8168
Epoch 3/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.5238 - acc: 0.8388
Epoch 00003: val_loss improved from 0.56306 to 0.51163, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 504us/step - loss: 0.5234 - acc: 0.8389 - val_loss: 0.5116 - val_acc: 0.8395
Epoch 4/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.4411 - acc: 0.8582
Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 3s 496us/step - loss: 0.4424 - acc: 0.8579 - val_loss: 0.5128 - val_acc: 0.8311
Epoch 5/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.4023 - acc: 0.8714
Epoch 00005: val_loss improved from 0.51163 to 0.48214, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 484us/step - loss: 0.4028 - acc: 0.8713 - val_loss: 0.4821 - val_acc: 0.8479
Epoch 6/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.3385 - acc: 0.8917
Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 3s 481us/step - loss: 0.3393 - acc: 0.8918 - val_loss: 0.4876 - val_acc: 0.8383
Epoch 7/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.3232 - acc: 0.8969
Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 3s 490us/step - loss: 0.3233 - acc: 0.8969 - val_loss: 0.4842 - val_acc: 0.8491
Epoch 8/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2828 - acc: 0.9090
Epoch 00008: val_loss improved from 0.48214 to 0.47469, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 457us/step - loss: 0.2843 - acc: 0.9082 - val_loss: 0.4747 - val_acc: 0.8455
Epoch 9/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2687 - acc: 0.9073
Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 3s 496us/step - loss: 0.2681 - acc: 0.9076 - val_loss: 0.4765 - val_acc: 0.8515
Epoch 10/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2322 - acc: 0.9244
Epoch 00010: val_loss improved from 0.47469 to 0.47380, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 493us/step - loss: 0.2324 - acc: 0.9243 - val_loss: 0.4738 - val_acc: 0.8551
Epoch 11/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2105 - acc: 0.9343
Epoch 00011: val_loss improved from 0.47380 to 0.46853, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 481us/step - loss: 0.2111 - acc: 0.9343 - val_loss: 0.4685 - val_acc: 0.8575
Epoch 12/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.2002 - acc: 0.9345
Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 3s 478us/step - loss: 0.1998 - acc: 0.9346 - val_loss: 0.4718 - val_acc: 0.8539
Epoch 13/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1792 - acc: 0.9396
Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 3s 491us/step - loss: 0.1791 - acc: 0.9397 - val_loss: 0.4718 - val_acc: 0.8491
Epoch 14/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1653 - acc: 0.9467
Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 3s 487us/step - loss: 0.1649 - acc: 0.9469 - val_loss: 0.4914 - val_acc: 0.8467
Epoch 15/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1494 - acc: 0.9536
Epoch 00015: val_loss improved from 0.46853 to 0.46763, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 488us/step - loss: 0.1490 - acc: 0.9537 - val_loss: 0.4676 - val_acc: 0.8503
Epoch 16/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1401 - acc: 0.9542
Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 3s 478us/step - loss: 0.1405 - acc: 0.9540 - val_loss: 0.4849 - val_acc: 0.8491
Epoch 17/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1401 - acc: 0.9554
Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 3s 492us/step - loss: 0.1397 - acc: 0.9555 - val_loss: 0.4686 - val_acc: 0.8587
Epoch 18/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1169 - acc: 0.9641
Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 3s 493us/step - loss: 0.1177 - acc: 0.9639 - val_loss: 0.4739 - val_acc: 0.8527
Epoch 19/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1530 - acc: 0.9534
Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 3s 475us/step - loss: 0.1527 - acc: 0.9536 - val_loss: 0.4697 - val_acc: 0.8515
Epoch 20/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1129 - acc: 0.9648
Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 3s 499us/step - loss: 0.1131 - acc: 0.9647 - val_loss: 0.4815 - val_acc: 0.8467
Epoch 21/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.1134 - acc: 0.9669
Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 3s 475us/step - loss: 0.1132 - acc: 0.9671 - val_loss: 0.4761 - val_acc: 0.8575
Epoch 22/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0990 - acc: 0.9703
Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 3s 453us/step - loss: 0.0990 - acc: 0.9702 - val_loss: 0.4784 - val_acc: 0.8467
Epoch 23/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0990 - acc: 0.9706
Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 3s 518us/step - loss: 0.0990 - acc: 0.9705 - val_loss: 0.4899 - val_acc: 0.8575
Epoch 24/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0928 - acc: 0.9718
Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 3s 472us/step - loss: 0.0929 - acc: 0.9717 - val_loss: 0.5125 - val_acc: 0.8479
Epoch 25/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0917 - acc: 0.9722
Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 3s 475us/step - loss: 0.0915 - acc: 0.9722 - val_loss: 0.5028 - val_acc: 0.8527
Epoch 26/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0943 - acc: 0.9713
Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 3s 486us/step - loss: 0.0943 - acc: 0.9713 - val_loss: 0.5109 - val_acc: 0.8443
Epoch 27/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0870 - acc: 0.9719
Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 3s 462us/step - loss: 0.0867 - acc: 0.9720 - val_loss: 0.5110 - val_acc: 0.8575
Epoch 28/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0765 - acc: 0.9760
Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 3s 478us/step - loss: 0.0763 - acc: 0.9760 - val_loss: 0.5136 - val_acc: 0.8587
Epoch 29/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0729 - acc: 0.9785
Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 3s 506us/step - loss: 0.0730 - acc: 0.9786 - val_loss: 0.4878 - val_acc: 0.8551
Epoch 30/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0782 - acc: 0.9742
Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 3s 468us/step - loss: 0.0785 - acc: 0.9740 - val_loss: 0.5077 - val_acc: 0.8515
Epoch 31/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0834 - acc: 0.9761
Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 3s 489us/step - loss: 0.0834 - acc: 0.9760 - val_loss: 0.5120 - val_acc: 0.8599
Epoch 32/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0717 - acc: 0.9787
Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 3s 491us/step - loss: 0.0719 - acc: 0.9786 - val_loss: 0.5171 - val_acc: 0.8515
Epoch 33/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0747 - acc: 0.9775
Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 3s 471us/step - loss: 0.0750 - acc: 0.9774 - val_loss: 0.5412 - val_acc: 0.8503
Epoch 34/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0749 - acc: 0.9769
Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 3s 493us/step - loss: 0.0748 - acc: 0.9768 - val_loss: 0.5121 - val_acc: 0.8479
Epoch 35/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0609 - acc: 0.9815
Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 3s 489us/step - loss: 0.0608 - acc: 0.9816 - val_loss: 0.5161 - val_acc: 0.8539
Epoch 36/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0570 - acc: 0.9835
Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 3s 491us/step - loss: 0.0572 - acc: 0.9832 - val_loss: 0.5167 - val_acc: 0.8575
Epoch 37/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0709 - acc: 0.9796
Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 3s 485us/step - loss: 0.0708 - acc: 0.9796 - val_loss: 0.5068 - val_acc: 0.8551
Epoch 38/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0568 - acc: 0.9830
Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 3s 456us/step - loss: 0.0566 - acc: 0.9831 - val_loss: 0.5268 - val_acc: 0.8503
Epoch 39/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0564 - acc: 0.9847
Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 3s 499us/step - loss: 0.0564 - acc: 0.9847 - val_loss: 0.5412 - val_acc: 0.8587
Epoch 40/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.0477 - acc: 0.9865
Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 3s 491us/step - loss: 0.0478 - acc: 0.9865 - val_loss: 0.5140 - val_acc: 0.8527

Xception Test accuracy: 86.4833%

Test VGG19

In [115]:
evaluate_model('VGG19')
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6144/6680 [==========================>...] - ETA: 0s - loss: 11.2693 - acc: 0.0667
Epoch 00001: val_loss improved from inf to 3.72060, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 289us/step - loss: 10.9012 - acc: 0.0711 - val_loss: 3.7206 - val_acc: 0.2611
Epoch 2/40
6144/6680 [==========================>...] - ETA: 0s - loss: 4.3036 - acc: 0.1823
Epoch 00002: val_loss improved from 3.72060 to 3.32851, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s 76us/step - loss: 4.2450 - acc: 0.1850 - val_loss: 3.3285 - val_acc: 0.3305
Epoch 3/40
6656/6680 [============================>.] - ETA: 0s - loss: 3.0732 - acc: 0.3030
Epoch 00003: val_loss improved from 3.32851 to 2.08408, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 71us/step - loss: 3.0707 - acc: 0.3033 - val_loss: 2.0841 - val_acc: 0.5222
Epoch 4/40
6400/6680 [===========================>..] - ETA: 0s - loss: 2.4116 - acc: 0.4152
Epoch 00004: val_loss improved from 2.08408 to 1.54634, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 66us/step - loss: 2.4017 - acc: 0.4171 - val_loss: 1.5463 - val_acc: 0.5976
Epoch 5/40
6656/6680 [============================>.] - ETA: 0s - loss: 1.9984 - acc: 0.4862
Epoch 00005: val_loss improved from 1.54634 to 1.28888, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 71us/step - loss: 1.9970 - acc: 0.4862 - val_loss: 1.2889 - val_acc: 0.6647
Epoch 6/40
5632/6680 [========================>.....] - ETA: 0s - loss: 1.7553 - acc: 0.5334
Epoch 00006: val_loss improved from 1.28888 to 1.12088, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 68us/step - loss: 1.7363 - acc: 0.5367 - val_loss: 1.1209 - val_acc: 0.6838
Epoch 7/40
6144/6680 [==========================>...] - ETA: 0s - loss: 1.5147 - acc: 0.5752
Epoch 00007: val_loss improved from 1.12088 to 1.03119, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 64us/step - loss: 1.5110 - acc: 0.5768 - val_loss: 1.0312 - val_acc: 0.7126
Epoch 8/40
6144/6680 [==========================>...] - ETA: 0s - loss: 1.3837 - acc: 0.6178
Epoch 00008: val_loss improved from 1.03119 to 0.99243, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 72us/step - loss: 1.3901 - acc: 0.6160 - val_loss: 0.9924 - val_acc: 0.7066
Epoch 9/40
5632/6680 [========================>.....] - ETA: 0s - loss: 1.2829 - acc: 0.6445
Epoch 00009: val_loss improved from 0.99243 to 0.90862, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 69us/step - loss: 1.2811 - acc: 0.6452 - val_loss: 0.9086 - val_acc: 0.7293
Epoch 10/40
5888/6680 [=========================>....] - ETA: 0s - loss: 1.1980 - acc: 0.6591
Epoch 00010: val_loss improved from 0.90862 to 0.87498, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 66us/step - loss: 1.1909 - acc: 0.6632 - val_loss: 0.8750 - val_acc: 0.7437
Epoch 11/40
6144/6680 [==========================>...] - ETA: 0s - loss: 1.1108 - acc: 0.6774
Epoch 00011: val_loss improved from 0.87498 to 0.84602, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 63us/step - loss: 1.1109 - acc: 0.6778 - val_loss: 0.8460 - val_acc: 0.7629
Epoch 12/40
5888/6680 [=========================>....] - ETA: 0s - loss: 1.0303 - acc: 0.6943
Epoch 00012: val_loss improved from 0.84602 to 0.80580, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 73us/step - loss: 1.0307 - acc: 0.6975 - val_loss: 0.8058 - val_acc: 0.7545
Epoch 13/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.9854 - acc: 0.7025
Epoch 00013: val_loss improved from 0.80580 to 0.78999, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 61us/step - loss: 0.9748 - acc: 0.7063 - val_loss: 0.7900 - val_acc: 0.7569
Epoch 14/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.9132 - acc: 0.7235
Epoch 00014: val_loss improved from 0.78999 to 0.77613, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 61us/step - loss: 0.9193 - acc: 0.7220 - val_loss: 0.7761 - val_acc: 0.7677
Epoch 15/40
5632/6680 [========================>.....] - ETA: 0s - loss: 0.8846 - acc: 0.7377
Epoch 00015: val_loss improved from 0.77613 to 0.75923, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 72us/step - loss: 0.8854 - acc: 0.7364 - val_loss: 0.7592 - val_acc: 0.7689
Epoch 16/40
5888/6680 [=========================>....] - ETA: 0s - loss: 0.8463 - acc: 0.7378
Epoch 00016: val_loss improved from 0.75923 to 0.75640, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 62us/step - loss: 0.8319 - acc: 0.7416 - val_loss: 0.7564 - val_acc: 0.7677
Epoch 17/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.8252 - acc: 0.7480
Epoch 00017: val_loss improved from 0.75640 to 0.74942, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 60us/step - loss: 0.8240 - acc: 0.7497 - val_loss: 0.7494 - val_acc: 0.7629
Epoch 18/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.7411 - acc: 0.7679
Epoch 00018: val_loss improved from 0.74942 to 0.70955, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 71us/step - loss: 0.7410 - acc: 0.7680 - val_loss: 0.7096 - val_acc: 0.7820
Epoch 19/40
5888/6680 [=========================>....] - ETA: 0s - loss: 0.7301 - acc: 0.7797
Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 0s 66us/step - loss: 0.7432 - acc: 0.7737 - val_loss: 0.7260 - val_acc: 0.7749
Epoch 20/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.7243 - acc: 0.7744
Epoch 00020: val_loss improved from 0.70955 to 0.70844, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 66us/step - loss: 0.7239 - acc: 0.7753 - val_loss: 0.7084 - val_acc: 0.7772
Epoch 21/40
5888/6680 [=========================>....] - ETA: 0s - loss: 0.7014 - acc: 0.7836
Epoch 00021: val_loss improved from 0.70844 to 0.70069, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 73us/step - loss: 0.6989 - acc: 0.7855 - val_loss: 0.7007 - val_acc: 0.7737
Epoch 22/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.6404 - acc: 0.8020
Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 0s 65us/step - loss: 0.6404 - acc: 0.8019 - val_loss: 0.7060 - val_acc: 0.7928
Epoch 23/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.6241 - acc: 0.8039
Epoch 00023: val_loss improved from 0.70069 to 0.69016, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 64us/step - loss: 0.6242 - acc: 0.8009 - val_loss: 0.6902 - val_acc: 0.7964
Epoch 24/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.5910 - acc: 0.8120
Epoch 00024: val_loss improved from 0.69016 to 0.68485, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 0s 71us/step - loss: 0.5970 - acc: 0.8103 - val_loss: 0.6848 - val_acc: 0.7940
Epoch 25/40
5632/6680 [========================>.....] - ETA: 0s - loss: 0.6148 - acc: 0.8033
Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 0s 65us/step - loss: 0.5952 - acc: 0.8075 - val_loss: 0.7178 - val_acc: 0.7844
Epoch 26/40
5632/6680 [========================>.....] - ETA: 0s - loss: 0.5721 - acc: 0.8168
Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 0s 66us/step - loss: 0.5672 - acc: 0.8187 - val_loss: 0.7215 - val_acc: 0.7796
Epoch 27/40
5888/6680 [=========================>....] - ETA: 0s - loss: 0.5315 - acc: 0.8288
Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 0s 65us/step - loss: 0.5372 - acc: 0.8268 - val_loss: 0.6868 - val_acc: 0.7772
Epoch 28/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.5882 - acc: 0.8130
Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 0s 73us/step - loss: 0.5879 - acc: 0.8111 - val_loss: 0.6925 - val_acc: 0.7868
Epoch 29/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.5423 - acc: 0.8270
Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 0s 60us/step - loss: 0.5376 - acc: 0.8284 - val_loss: 0.6849 - val_acc: 0.7880
Epoch 30/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.5277 - acc: 0.8324
Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 0s 59us/step - loss: 0.5290 - acc: 0.8322 - val_loss: 0.6968 - val_acc: 0.7976
Epoch 31/40
6656/6680 [============================>.] - ETA: 0s - loss: 0.5294 - acc: 0.8302
Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 0s 69us/step - loss: 0.5280 - acc: 0.8307 - val_loss: 0.6941 - val_acc: 0.7976
Epoch 32/40
5888/6680 [=========================>....] - ETA: 0s - loss: 0.5130 - acc: 0.8325
Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 0s 62us/step - loss: 0.5114 - acc: 0.8331 - val_loss: 0.6907 - val_acc: 0.7856
Epoch 33/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.4476 - acc: 0.8563
Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 0s 64us/step - loss: 0.4471 - acc: 0.8563 - val_loss: 0.6967 - val_acc: 0.7844
Epoch 34/40
5888/6680 [=========================>....] - ETA: 0s - loss: 0.4521 - acc: 0.8538
Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 0s 65us/step - loss: 0.4527 - acc: 0.8536 - val_loss: 0.6849 - val_acc: 0.7988
Epoch 35/40
5632/6680 [========================>.....] - ETA: 0s - loss: 0.4282 - acc: 0.8594
Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 0s 70us/step - loss: 0.4357 - acc: 0.8558 - val_loss: 0.7063 - val_acc: 0.7928
Epoch 36/40
5632/6680 [========================>.....] - ETA: 0s - loss: 0.4337 - acc: 0.8580
Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 0s 68us/step - loss: 0.4344 - acc: 0.8573 - val_loss: 0.6994 - val_acc: 0.7964
Epoch 37/40
5888/6680 [=========================>....] - ETA: 0s - loss: 0.4368 - acc: 0.8584
Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 1s 75us/step - loss: 0.4362 - acc: 0.8587 - val_loss: 0.7329 - val_acc: 0.7844
Epoch 38/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.4149 - acc: 0.8651
Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 0s 66us/step - loss: 0.4201 - acc: 0.8630 - val_loss: 0.7485 - val_acc: 0.7856
Epoch 39/40
5888/6680 [=========================>....] - ETA: 0s - loss: 0.3972 - acc: 0.8660
Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 0s 63us/step - loss: 0.3986 - acc: 0.8665 - val_loss: 0.7137 - val_acc: 0.7844
Epoch 40/40
6144/6680 [==========================>...] - ETA: 0s - loss: 0.4141 - acc: 0.8665
Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 0s 61us/step - loss: 0.4138 - acc: 0.8651 - val_loss: 0.6935 - val_acc: 0.7928

VGG19 Test accuracy: 77.3923%

Test LightGBM

In [105]:
from lightgbm import LGBMClassifier
lgbm = LGBMClassifier(objective='multiclass')
lgbm.fit(train_Resnet50.reshape((-1, train_Resnet50.shape[-1])), np.argmax(train_targets, axis=1),
        eval_set=(valid_Resnet50.reshape((-1, valid_Resnet50.shape[-1])), np.argmax(valid_targets, axis=1)), verbose=True)
[1]	valid_0's multi_logloss: 2.93992
[2]	valid_0's multi_logloss: 2.76174
[3]	valid_0's multi_logloss: 2.66124
[4]	valid_0's multi_logloss: 2.5714
[5]	valid_0's multi_logloss: 2.49337
[6]	valid_0's multi_logloss: 2.42221
[7]	valid_0's multi_logloss: 2.36437
[8]	valid_0's multi_logloss: 2.30971
[9]	valid_0's multi_logloss: 2.25785
[10]	valid_0's multi_logloss: 2.21151
[11]	valid_0's multi_logloss: 2.16577
[12]	valid_0's multi_logloss: 2.12489
[13]	valid_0's multi_logloss: 2.0899
[14]	valid_0's multi_logloss: 2.05487
[15]	valid_0's multi_logloss: 2.02101
[16]	valid_0's multi_logloss: 1.98921
[17]	valid_0's multi_logloss: 1.9581
[18]	valid_0's multi_logloss: 1.92964
[19]	valid_0's multi_logloss: 1.90176
[20]	valid_0's multi_logloss: 1.87688
[21]	valid_0's multi_logloss: 1.8503
[22]	valid_0's multi_logloss: 1.82647
[23]	valid_0's multi_logloss: 1.80308
[24]	valid_0's multi_logloss: 1.78055
[25]	valid_0's multi_logloss: 1.75879
[26]	valid_0's multi_logloss: 1.7369
[27]	valid_0's multi_logloss: 1.71522
[28]	valid_0's multi_logloss: 1.69388
[29]	valid_0's multi_logloss: 1.67296
[30]	valid_0's multi_logloss: 1.65246
[31]	valid_0's multi_logloss: 1.63437
[32]	valid_0's multi_logloss: 1.61799
[33]	valid_0's multi_logloss: 1.59937
[34]	valid_0's multi_logloss: 1.58228
[35]	valid_0's multi_logloss: 1.56495
[36]	valid_0's multi_logloss: 1.54784
[37]	valid_0's multi_logloss: 1.5321
[38]	valid_0's multi_logloss: 1.51681
[39]	valid_0's multi_logloss: 1.50213
[40]	valid_0's multi_logloss: 1.48398
[41]	valid_0's multi_logloss: 1.46967
[42]	valid_0's multi_logloss: 1.45707
[43]	valid_0's multi_logloss: 1.44233
[44]	valid_0's multi_logloss: 1.42942
[45]	valid_0's multi_logloss: 1.41579
[46]	valid_0's multi_logloss: 1.40486
[47]	valid_0's multi_logloss: 1.39258
[48]	valid_0's multi_logloss: 1.38039
[49]	valid_0's multi_logloss: 1.36892
[50]	valid_0's multi_logloss: 1.35807
[51]	valid_0's multi_logloss: 1.34697
[52]	valid_0's multi_logloss: 1.33513
[53]	valid_0's multi_logloss: 1.32485
[54]	valid_0's multi_logloss: 1.31462
[55]	valid_0's multi_logloss: 1.30541
[56]	valid_0's multi_logloss: 1.29726
[57]	valid_0's multi_logloss: 1.28844
[58]	valid_0's multi_logloss: 1.27971
[59]	valid_0's multi_logloss: 1.27257
[60]	valid_0's multi_logloss: 1.26519
[61]	valid_0's multi_logloss: 1.25793
[62]	valid_0's multi_logloss: 1.24948
[63]	valid_0's multi_logloss: 1.24174
[64]	valid_0's multi_logloss: 1.23414
[65]	valid_0's multi_logloss: 1.22663
[66]	valid_0's multi_logloss: 1.21862
[67]	valid_0's multi_logloss: 1.21193
[68]	valid_0's multi_logloss: 1.20495
[69]	valid_0's multi_logloss: 1.19754
[70]	valid_0's multi_logloss: 1.19189
[71]	valid_0's multi_logloss: 1.18555
[72]	valid_0's multi_logloss: 1.17954
[73]	valid_0's multi_logloss: 1.17398
[74]	valid_0's multi_logloss: 1.16976
[75]	valid_0's multi_logloss: 1.16649
[76]	valid_0's multi_logloss: 1.16208
[77]	valid_0's multi_logloss: 1.15719
[78]	valid_0's multi_logloss: 1.15398
[79]	valid_0's multi_logloss: 1.149
[80]	valid_0's multi_logloss: 1.14488
[81]	valid_0's multi_logloss: 1.14163
[82]	valid_0's multi_logloss: 1.13747
[83]	valid_0's multi_logloss: 1.13329
[84]	valid_0's multi_logloss: 1.12905
[85]	valid_0's multi_logloss: 1.12466
[86]	valid_0's multi_logloss: 1.12023
[87]	valid_0's multi_logloss: 1.1169
[88]	valid_0's multi_logloss: 1.113
[89]	valid_0's multi_logloss: 1.10931
[90]	valid_0's multi_logloss: 1.10395
[91]	valid_0's multi_logloss: 1.10149
[92]	valid_0's multi_logloss: 1.09764
[93]	valid_0's multi_logloss: 1.09399
[94]	valid_0's multi_logloss: 1.08955
[95]	valid_0's multi_logloss: 1.08722
[96]	valid_0's multi_logloss: 1.08275
[97]	valid_0's multi_logloss: 1.07833
[98]	valid_0's multi_logloss: 1.0739
[99]	valid_0's multi_logloss: 1.06959
[100]	valid_0's multi_logloss: 1.06506
Out[105]:
LGBMClassifier(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0,
        learning_rate=0.1, max_depth=-1, min_child_samples=20,
        min_child_weight=0.001, min_split_gain=0.0, n_estimators=100,
        n_jobs=-1, num_leaves=31, objective='multiclass',
        random_state=None, reg_alpha=0.0, reg_lambda=0.0, silent=True,
        subsample=1.0, subsample_for_bin=200000, subsample_freq=1)
In [110]:
lgbm_predictions = lgbm.predict(test_Resnet50.reshape((-1, test_Resnet50.shape[-1])))
test_accuracy = 100*np.sum(lgbm_predictions==np.argmax(test_targets, axis=1))/len(lgbm_predictions)
print('LightGBM Test accuracy: %.4f%%' % test_accuracy)
LightGBM Test accuracy: 72.9665%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [155]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline    

def display_image(img_path, url=False):
    if url:
        req = urllib.request.urlopen(img_path)
        arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
        img = cv2.imdecode(arr, -1) 
    else:
        img = cv2.imread(img_path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(cv_rgb)
    plt.show()
In [122]:
### DONE: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from extract_bottleneck_features import extract_InceptionV3
from extract_bottleneck_features import extract_Resnet50
from extract_bottleneck_features import extract_VGG16
from extract_bottleneck_features import extract_VGG19
from extract_bottleneck_features import extract_Xception

extract_bottleneck_features = {
    'InceptionV3': extract_InceptionV3,
    'Resnet50': extract_Resnet50,
    'VGG16': extract_VGG16,
    'VGG19': extract_VGG19,
    'Xception': extract_Xception
}

def predict_image(model_name, img_path):    
    img = preprocess_input(path_to_tensor(img_path))
    bottleneck_features = extract_bottleneck_features[model_name](img)
    
    model = Sequential()
    model.add(GlobalAveragePooling2D(input_shape=bottleneck_features.shape[1:]))
    model.add(Dropout(0.3))
    model.add(Dense(512, activation='relu'))
    model.add(Dropout(0.3))
    model.add(Dense(133, activation='softmax'))
    model.load_weights(f'saved_models/weights.best.{model_name}.hdf5')
    
    return dog_names[np.argmax(model.predict(bottleneck_features))]
In [120]:
sns.reset_orig()
In [82]:
import random
file = random.choice(test_files)
print(file)
display_image(file)
predict_image('Xception', file)
dogImages/test/050.Chinese_shar-pei/Chinese_shar-pei_03556.jpg
Out[82]:
'Chinese_shar-pei'

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [157]:
### DONE: Write your algorithm.
### Feel free to use as many code cells as needed.
def detect_image(img_path, model_name='Xception', url=False):
    if dog_detector(img_path, url):
        return f"It's a {predict_image(model_name, img_path)}!"
    elif dnn_face_detector(img_path, 0.99, url):
        return f"You look like a {predict_image(model_name, img_path)}!"
    else:
        return "Error: the image could not be recognized"
In [134]:
import random
file = random.choice(human_files) # or human_files
print(file)
display_image(file)
detect_image(file, 'Xception')
lfw/Lord_Hutton/Lord_Hutton_0002.jpg
Out[134]:
'You look like a Cavalier_king_charles_spaniel!'

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: The algorithm was able to match nearly all the dog images with their breed, except in cases where the images were not part of any of the 133 classes. As for the human face matching, it is hard to know what resembling dog breed to expect, so the output was very diverse. In order to improve the algorithm, data augmentation is always a good method for reducing overfitting. After this, hyperparameter tuning, such as weight initialization method can helping for the optimization. Furthermore, in order to improve the optimization of the neural network, more techniques for adjusting the learning rate can be useful, such as cyclical learning rates (1).

  1. 2015 - Leslie N. Smith. Cyclical Learning Rates for Training Neural Networks
In [158]:
## DONE: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
def run_detector(img_path, model_name='Xception', url=False):
    print(img_path)
    display_image(img_path, url)
    return detect_image(img_path, model_name, url)
In [166]:
run_detector('lfw/Michael_Jackson/Michael_Jackson_0006.jpg')
lfw/Michael_Jackson/Michael_Jackson_0006.jpg
Out[166]:
'You look like a Dachshund!'
In [167]:
run_detector('test_samples/chihuahua.jpg')
test_samples/chihuahua.jpg
Out[167]:
"It's a Chihuahua!"
In [172]:
run_detector('test_samples/muffin.jpg')
test_samples/muffin.jpg
Out[172]:
"It's a Chinese_crested!"
In [173]:
run_detector('test_samples/labradoodle.jpg')
test_samples/labradoodle.jpg
Out[173]:
"It's a Kuvasz!"
In [174]:
run_detector('test_samples/snapchat.jpg')
test_samples/snapchat.jpg
Out[174]:
'You look like a Doberman_pinscher!'
In [182]:
run_detector('test_samples/beagle.jpg')
test_samples/beagle.jpg
Out[182]:
"It's a Beagle!"
In [184]:
run_detector('test_samples/shibe.jpg')
test_samples/shibe.jpg
Out[184]:
"It's a Akita!"
In [191]:
run_detector('test_samples/arnold.jpg')
test_samples/arnold.jpg
Out[191]:
'You look like a Chinese_crested!'
In [175]:
run_detector('test_samples/cat.jpg')
test_samples/cat.jpg
Out[175]:
"It's a Maltese!"
In [176]:
run_detector('test_samples/doge.jpg')
test_samples/doge.jpg
Out[176]:
'Error: the image could not be recognized'
In [192]:
run_detector('test_samples/cat2.jpg')
test_samples/cat2.jpg
Out[192]:
'Error: the image could not be recognized'
In [179]:
run_detector('test_samples/german_shepherd.jpg')
test_samples/german_shepherd.jpg
Out[179]:
"It's a Canaan_dog!"